package springcloud.controller;

import cn.xjt.pojo.Dept;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import springcloud.service.DeptService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 内容：
 *
 * @author
 * @date 2021/2/27-16:57
 */

@RestController
public class DeptController extends BaseController{

	@Autowired
	DeptService deptService;

	@Autowired
	DiscoveryClient client;

	@RequestMapping(value = "/queryOne/{id}",method = RequestMethod.GET)
	@HystrixCommand(fallbackMethod = "hystrixGet")				//开始熔断机制，当方法出现错误，会调用错误回调方法，备选方法
	public Dept get(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id){
		Dept dept = deptService.selectDept(id);
		if (dept==null){
			throw new RuntimeException("当前id信息为空");
		}
		return dept;
	}

	public Dept hystrixGet(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id){
		return new Dept().setDeptno(id).setName("当前id信息为空，或信息不存在。请验证后重试").setDb_source("no Db_source in this Mysql");
	}

	/**
	 * 注册进来的微服务，获取微服务的信息
	 * @return
	 */
	@GetMapping("/getinfo")
	public Object get(){
		List<String> services = client.getServices();
		System.out.println("Discovery=>"+services);
		List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
		System.out.println(instances);
		return instances;
	}
}
